#include "inner.h"
#include "fv.h"
#include <string.h>

struct fv_box *fv_hbox(struct fv_box *outer, int n)
{
    if (outer == NULL || n < 1)
        return NULL;

    struct fv_box *box = (struct fv_box *)fv_malloc(sizeof(struct fv_box) * n);
    if (box == NULL)
        return NULL;;

    memset(box, 0, sizeof(*box));
    outer->nbox = n;
    outer->box = box;
    outer->orientation = 'H';

    for (int i = 0; i < n; i++) {
        box[i].ratio = 1.0f / n;
    }

    return box;
}

struct fv_box *fv_vbox(struct fv_box *outer, int n)
{
    struct fv_box *box = fv_hbox(outer, n);
    if (box == NULL)
        return NULL;

    box->orientation = 'V';
    return box;
}

static int layout_single(struct fv_box *box)
{
    if (box->orientation == 'H') {
        for (int i = 0; i < box->nbox; i++) {
            box->box[i].w = (int)(box->w * box->box[i].ratio);
            box->box[i].h = box->h;
        }
    } else if (box->orientation == 'V') {
        for (int i = 0; i < box->nbox; i++) {
            box->box[i].h = (int)(box->h * box->box[i].ratio);
            box->box[i].w = box->w;
        }
    }

    return 0;
}

static int layout_each(struct fv_box *box)
{
    if (box->orientation != 'H' && box->orientation != 'V')
        return;

    layout_single(box);

    for (int i = 0; i < box->nbox; i++) {
        layout_each(&box->box[i]);
    }
}

void fv_layout()
{
    layout_each(&fvglob.box); // run layout start from root box
}

